package com.letv.android.client.album.controller;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;

import com.letv.ads.ADPlayFragment;
import com.letv.ads.AdsManager;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.client.controller.AlbumGestureObservable;
import com.letv.android.client.fragment.AlbumRoomPlayFragment;
import com.letv.android.client.listener.OrientationSensorListener;
import com.letv.android.client.utils.ChangeOrientationHandler;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.listener.PlayAdFragmentListener;
import com.letv.core.bean.VideoBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.ActivityUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.PageIdConstant;

/**
 * 点播控制器
 *
 * @author zhuqiao
 */
public class AlbumRoomController {
    private AlbumPlayRoomActivity mActivity;

    // 转屏Listener
    private OrientationSensorListener mOrientationSensorListener;
    private SensorManager mSensorManager;

    // 全景陀螺仪，重力感应
    private SensorEventListener mPanoramaSensorListener, mPanoramaSensorListenerG;

    public AlbumRoomController(AlbumPlayRoomActivity activity) {
        mActivity = activity;
    }

    /**
     * 初始化默认陀螺仪
     */
    public void initDefaultSensor() {
        Handler orientationHandler = new ChangeOrientationHandler(mActivity);
        mSensorManager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mOrientationSensorListener = new OrientationSensorListener(orientationHandler, mActivity);

        mSensorManager.registerListener(mOrientationSensorListener, sensor, SensorManager.SENSOR_DELAY_GAME);
    }

    /**
     * 初始化全景陀螺仪
     */
    private void initPanoramaSensor() {
        // mSensorManager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
        // Sensor orientationSensorG = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        // mPanoramaSensorListener = new SensorEventListener() {
        //
        // @Override
        // public void onSensorChanged(SensorEvent event) {
        // float axisX = event.values[0];// (Math.PI*2))*360;
        // float axisY = event.values[1];// (Math.PI*2))*360;
        // float axisZ = event.values[2];// (Math.PI*2))*360;
        //
        // if (mActivity.getAlbumPlayFragment() != null && mActivity.getAlbumPlayFragment().getVideoView() != null) {
        // try {
        // mActivity.getAlbumPlayFragment().getVideoView().setgravity_yroInfomation(axisX, axisY, axisZ);
        // } catch (Exception e) {
        // }
        // }
        // }
        //
        // @Override
        // public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //
        // }
        //
        // };
        // mPanoramaSensorListenerG = new SensorEventListener() {
        //
        // @Override
        // public void onSensorChanged(SensorEvent event) {
        // float gx = event.values[0];
        // float gy = event.values[1];
        // float gz = event.values[2];
        //
        // if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
        // if (mActivity.getAlbumPlayFragment() != null
        // && mActivity.getAlbumPlayFragment().getVideoView() != null) {
        // try {
        // mActivity.getAlbumPlayFragment().getVideoView().setGravityInfomation(gx, gy, gz);
        // } catch (Exception e) {
        // }
        // }
        // }
        //
        // int orientation = -1;
        // float magnitude = gx * gx + gy * gy;
        // // Don't trust the angle if the magnitude is small compared to the y
        // // value
        // if (magnitude * 4 >= gz * gz) {
        // float OneEightyOverPi = 57.29577957855f;
        // float angle = (float) Math.atan2(-gy, gx) * OneEightyOverPi;
        // orientation = 90 - (int) Math.round(angle);
        // // normalize to 0 - 359 range
        // while (orientation >= 360) {
        // orientation -= 360;
        // }
        // while (orientation < 0) {
        // orientation += 360;
        // }
        // }
        //
        // if (orientation >= 60 && orientation <= 120) {
        // LogInfo.log("zhuqiao", "正横屏");
        // } else if (orientation > 150 && orientation < 210) {
        // LogInfo.log("zhuqiao", "正竖屏");
        // } else if (orientation > 240 && orientation < 300) {
        // LogInfo.log("zhuqiao", "反横屏");
        // } else if ((orientation > 330 && orientation < 360)) {
        // LogInfo.log("zhuqiao", "反竖屏");
        // }
        // }
        //
        // @Override
        // public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // }
        // };
        // mSensorManager.registerListener(mPanoramaSensorListener,
        // mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
        // mSensorManager.registerListener(mPanoramaSensorListenerG, orientationSensorG,
        // SensorManager.SENSOR_DELAY_GAME);
    }

    public boolean fullBack() {
        if (mActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mActivity.mIs4dVideo
            || mActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
            mActivity.getController().back();
            return true;
        }

        return false;
    }

    /**
     * 返回
     */
    public void back() {
        // back將输入法隐藏 by zhanghongfei 2015/1/18.
        InputMethodManager manager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (mActivity.getCurrentFocus() != null && mActivity.getCurrentFocus().getWindowToken() != null) {
            manager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
        }

        if (mActivity.getFlow() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();

        // zhudeshuai:添加三方调起返回逻辑
        if (flow.getFrom() == PlayConstant.LAUNCH_FROM_MSITE) {
            LogInfo.log("zhuqiao", "back:" + flow.isBackToOriginalApp());
            if (flow.isBackToOriginalApp()) {
                ActivityUtils.getInstance().removeAll();
            } else {
                String scheme = "video://video";
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.putExtra("from_M", true);
                intent.setData(Uri.parse(scheme));
                mActivity.startActivity(intent);
                mActivity.finish();
            }

            return;
        }

        String userClickBackTime = "";
        long userClickBackStartTime = 0l;
        if (mActivity.getFullControllerFragment() != null) {
            userClickBackTime = mActivity.getFullControllerFragment().getUserClickBackTime();
            userClickBackStartTime = mActivity.getFullControllerFragment().getUserClickBackStartTime();
        }
        if (TextUtils.isEmpty(userClickBackTime) && mActivity.getHalfControllerFragment() != null) {
            userClickBackTime = mActivity.getHalfControllerFragment().getUserClickBackTime();
            userClickBackStartTime = mActivity.getHalfControllerFragment().getUserClickBackStartTime();
        }
        if (TextUtils.isEmpty(userClickBackTime)) {
            userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
            userClickBackStartTime = System.currentTimeMillis();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("time=").append(userClickBackTime).append("&");
        if (StringUtils.staticticsLoadTimeInfoFormat(System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
            sb.append("ut=").append("-").append("&");
        } else {
            sb.append("ut=")
                .append(StringUtils.staticticsLoadTimeInfoFormat(System.currentTimeMillis()
                    - userClickBackStartTime)).append("&");
        }
        if (flow.getLaunchMode() == PlayConstant.PLAY_DOWNLOAD || flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
            sb.append("pageid=").append(PageIdConstant.fullPlayPage);
        } else {
            sb.append("pageid=").append(PageIdConstant.halpPlayPage);
        }
        String cid = "";
        try {
            cid = (flow.getPlayingVideo() != null) ? String.valueOf(flow.getPlayingVideo().getCid()) : "-";
            // 统计
            DataStatistics.getInstance()
                          .sendActionInfo(mActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb
                                          .toString(),
                "0", cid + "", null, flow.getVid() + "", LetvUtils.getUID(), null, null, null, null,
                PreferencesManager.getInstance(mActivity).isLogin() ? 0 : 1, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mActivity.finish();
//        finishPlayer();

        /**
         * 5.6需求：点播在按返回键的时候增加页面的曝光上报
         */
        try {
            // 直播中的回看播放源
            // 推送过来的视频直接
            String pageId = StatisticsUtils.getPageId();
            String fl = StatisticsUtils.getFl();
            if (!TextUtils.isEmpty(pageId) && !pageId.equals("053") && flow.getFrom() == PlayConstant.LAUNCH_FROM_VCR) {
                StatisticsUtils.staticticsInfoPost(mActivity, "19", fl, null, -1, null, pageId, cid, null,
                    flow.getVid() + "", null, null);
                LogInfo.LogStatistics("点播-->回看：fl=" + fl + " ,pageid=" + pageId + " ,cid=" + cid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 切到全屏
     */
    public void full() {
        lockOnce(mActivity.getRequestedOrientation());
        UIsUtils.setScreenLandscape(mActivity);
        refreshLandspaceWhenLock();
    }

    /**
     * 全屏并且锁定
     */
    public void fullLock() {
        setLock(true);
        UIsUtils.setScreenLandscape(mActivity);
    }

    /**
     * 切到半屏
     */
    public void half() {
        lockOnce(mActivity.getRequestedOrientation());
        UIsUtils.setScreenPortrait(mActivity);

        // 统计
        String userClickBackTime = "";
        long userClickBackStartTime = 0l;
        if (mActivity.getFullControllerFragment() != null) {
            userClickBackTime = mActivity.getFullControllerFragment().getUserClickBackTime();
            userClickBackStartTime = mActivity.getFullControllerFragment().getUserClickBackStartTime();
        }

        if (TextUtils.isEmpty(userClickBackTime)) {
            userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
            userClickBackStartTime = System.currentTimeMillis();
        }
        StringBuilder sb = new StringBuilder();
        if (userClickBackTime == null) {
            sb.append("time=").append("-").append("&");
        } else {
            sb.append("time=").append(userClickBackTime).append("&");
        }
        if (StringUtils.staticticsLoadTimeInfoFormat(System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
            sb.append("ut=").append("-").append("&");
        } else {
            sb.append("ut=")
                .append(StringUtils.staticticsLoadTimeInfoFormat(System.currentTimeMillis()
                    - userClickBackStartTime)).append("&");
        }
        sb.append("pageid=").append(PageIdConstant.fullPlayPage);

        String cid = "";
        String vid = "";
        if (mActivity.getFlow() == null || mActivity.getFlow().getPlayingVideo() == null) {
            cid = "-";
            vid = "-";
            LogInfo.LogStatistics("cid or vid is null!");
        } else {
            cid = mActivity.getFlow().getPlayingVideo().getCid() + "";
            vid = mActivity.getFlow().getPlayingVideo().getVid() + "";
        }
        DataStatistics.getInstance()
                      .sendActionInfo(mActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb.toString(),
            "0", cid, null, vid, LetvUtils.getUID(), null, null, null, null,
            PreferencesManager.getInstance(mActivity).isLogin() ? 0 : 1, null);
    }

    /**
     * 暂停
     */
    public void pause(boolean showPauseVideo) {
        if (mActivity.getFlow() == null || mActivity.getAlbumPlayFragment() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();
        AlbumRoomPlayFragment playFragment = mActivity.getAlbumPlayFragment();

        playFragment.pause();

        if (flow.getPlayingVideo() == null || !showPauseVideo || playFragment.mIsSeekByUser) {// 点进度条的位置快进快退的时候不显示暂停广告
            return;
        }

        VideoBean video = flow.getPlayingVideo();

        if (!flow.isDownloadFile() && !video.needPay() && !AlbumPlayRoomActivity.sIsShowingLongwatch
            && !AlbumPlayRoomActivity.sIsBlockPause && mActivity.getPlayAdListener() != null) {
            // 得到暂停广告
            AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
            mActivity.getPlayAdListener().getDemandPauseAd(video.getCid(), flow.getAid(), flow.getVid(),
                video.getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity).getUserId(),
                video.getDuration() + "", "", "0");
        }
        if (video.needPay()) {
//            if (flow instanceof AlbumPlayTopicFlow) {
//                AdsManager.getInstance().setFromPush(LetvApplication.getInstance().isPush());
//                AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
//            }
            AdsManager.getInstance().getFrontVipAd(mActivity, video.getCid(), flow.getAid(), flow.getVid(),
                video.getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity).getUserId(),
                video.getDuration() + "", "", "0", video.needPay(), true, "6");// 上报广告动作
        }
    }

    /**
     * 开始
     */
    public void start() {
        if (mActivity.getFlow() == null || mActivity.getPlayAdListener() == null
            || mActivity.getAlbumPlayFragment() == null) {
            return;
        }

        AlbumPlayFlow flow = mActivity.getFlow();
        PlayAdFragmentListener adListener = mActivity.getPlayAdListener();
        AlbumRoomPlayFragment playFragment = mActivity.getAlbumPlayFragment();

        playFragment.setEnforcementPause(false);
        flow.setIsPauseAdIsShow(false);

        if (flow.isDownloadFile() && playFragment.getPlayingHandler() != null
            && mActivity.getFlow().getPlayInfo().currTime != 0) {
            playFragment.start();
        } else if (adListener instanceof AlbumPlayAdController
            && ((AlbumPlayAdController) adListener).getAdFragment() != null) {
            ADPlayFragment adFragment = ((AlbumPlayAdController) adListener).getAdFragment();
            adFragment.closePauseAd();

            if (adFragment.isPauseAd()) {
                if (flow.isAlreadyPlayAd()) {
                    return;
                }

                adListener.setADPause(false);
                adListener.setPauseAd(false);
                flow.getPlayInfo().mAdConsumeTime = System.currentTimeMillis();
                // flow.getPlayInfo().mAdsPlayFirstFrameTime = adFragment.getAdsPlayFirstFrameTime();
                // flow.getPlayInfo().mAdsInteractiveTimeInFact = adFragment.getAdsInteractiveTimeInFact();
                if (flow.getPlayingVideo() != null) {
                    VideoBean video = flow.getPlayingVideo();
                    adListener.getDemandFrontAd(video.getCid(), flow.getAid(), flow.getVid(), video.getMid(),
                        flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity).getUserId(),
                            video.getDuration() + "", "", "0", LetvSDK.getPinjie(),
                        video.needPay(), false, true, flow.isWo3GUser(), PreferencesManager.getInstance(mActivity).getUtp());
                }
            } else {
                if (!adListener.isPlaying()) {
                    if (playFragment.getVideoView() == null || !playFragment.getVideoView().isPaused()) {
                        if (mActivity.getLoadListener() != null) {
                            mActivity.getLoadListener().loadingVideo(null);
                        }
                    }
                    playFragment.setEnforcementWait(false);
                }

                adListener.setPauseAd(false);
                playFragment.start();
                // }
            }
        }
    }

    public void finishPlayer() {
        finishPlayer(false);
    }

    public void finishPlayer(boolean isJumpToPip) {
        // if (MainActivityGroup.getInstance() != null) {
        // if (MainActivityGroup.getInstance().isFromBaiduAndLesoAndWandoujia()) {
        // MainActivityGroup.getInstance().finish();
        // }
        // MainActivityGroup.getInstance().setThirdPartName(null);
        // }
        //

        // 判断是否是跳直播
//        if (!LiveLaunchUtils.checkJumpLive(mActivity, isJumpToPip)) {
//            mActivity.finish();
//            LetvApplication.getInstance().setPlayerFavouriteClick(true);
//        }

        mActivity.finishPlayer();
//        mActivity.finish();
    }

    /**
     * 锁屏
     *
     * @param isLock
     */
    public void setLock(boolean isLock) {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.setLock(isLock);
        }
    }

    /**
     * 锁屏一次
     *
     * @param orientation
     */
    public void lockOnce(int orientation) {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.lockOnce(orientation);
        }
    }

    /**
     * 是否锁屏
     *
     * @return
     */
    public boolean isLock() {
        if (mOrientationSensorListener != null) {
            return mOrientationSensorListener.isLock();
        }

        return false;
    }

    private void refreshLandspaceWhenLock() {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.refreshLandspaceWhenLock();
        }
    }

    public void onDestory() {
        if (mSensorManager != null) {
            if (mOrientationSensorListener != null) {
                mSensorManager.unregisterListener(mOrientationSensorListener);
            }

            if (mPanoramaSensorListener != null) {
                mSensorManager.unregisterListener(mPanoramaSensorListener);
            }
            if (mPanoramaSensorListenerG != null) {
                mSensorManager.unregisterListener(mPanoramaSensorListenerG);
            }
        }
    }

    public void onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return;
        }
        if (mActivity.getGestureController() != null) {
            int volNum = mActivity.getGestureController().getCurSoundVolume();
            boolean isUp = false;
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                volNum += 1;
                isUp = true;
            } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                volNum -= 1;
                isUp = false;
            }
            // 发送通知
            mActivity.getGestureObservable().notifyObservers(
                new AlbumGestureObservable.VolumeChangeNotify(mActivity.getGestureController().getMaxSoundVolume(), volNum,
                    isUp ? VolumnChangeStyle.UP : VolumnChangeStyle.DOWN));
            if (mActivity.getPlayAdListener() != null && mActivity.getPlayAdListener().getAdFragment() != null) {
                mActivity.getPlayAdListener().getAdFragment().setMuteViewStatus(volNum);
            }
        }
    }

    public void onResume() {
        if (mActivity.getFlow() != null && mActivity.getFlow().getPlayingVideo() != null
            && mActivity.getFlow().getPlayingVideo().needPay() && mActivity.getVipTrailListener() != null) {
            // 付费视频试看
            if (PreferencesManager.getInstance(mActivity).isLogin()) {
                if (!PreferencesManager.getInstance(mActivity).isVip()) {
                    // 登录成功非会员
                    mActivity.getVipTrailListener().setStateForStartByHasLogined(true);
                    mActivity.getVipTrailListener().checkVipTrailIsStateEnd();
                } else {
                    // 会员登录成功
                    mActivity.getVipTrailListener().finish();
                    mActivity.getFlow().retryPlay(true, false);
                }
            }
        }
    }
}
